package com.sxfq.loansupermarket.backsystem.modular.remoteSynergy.controller;

import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Dept;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.CaseSelectionIntelligentScoreInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.IconInfo;
import com.sxfq.loansupermarket.backsystem.modular.qualityAssurance.entity.QualityAssuranceInfo;
import com.sxfq.loansupermarket.backsystem.modular.websocket.WebSocketProgress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static org.apache.commons.io.FileUtils.getFile;
import static org.aspectj.util.FileUtil.copyFile;

/**
 * 智能评价
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/intelligent")
public class IntelliGenceController extends BaseController {
    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    WebSocketProgress webSocketProgress;

    /**
     * 病例评选图片智能评价
     */
    @RequestMapping(value = "/evaluation", method = RequestMethod.POST)
    @ResponseBody
    public int addCustomerMarket(@RequestBody CaseSelectionIntelligentScoreInfo info) throws Exception {
        String command = "D:\\华科_部署\\score_pro\\teeth_score\\application.py";   // python程序的路径
        String selCur = "select id,abbreviation from dept where simplename='" + info.getArrivalStore() + "'";
        Dept dept = sqlMapper.selectOne(selCur, Dept.class);
        String abbreviation = dept.getAbbreviation();
        String time[] = info.getTime();
        String num[] = info.getNums();
        String fileTime = "";
        String realUrl = "";
        String newPath = "";
        String realNewPath = "";
        //智能评分后，要删除临时文件夹路径，避免勾选评分时无效
        String path = "D:\\8068\\apache-tomcat-8.0.30\\webapps\\ROOT\\imageScore\\" + abbreviation + "\\";
        File fi = new File(path);//文件所在的路径
        deleteDirectory(fi);
        for (int i = 0; i < time.length; i++) {
            fileTime = "JPG_" + time[i];
            realUrl = "D:\\8068\\apache-tomcat-8.0.30\\webapps\\ROOT\\photoScoring\\" + abbreviation + "\\" + fileTime + "\\";
            File file = new File(realUrl);
            System.out.println(file.exists());
            if (!file.exists()) {
                System.out.println("文件夹没有该日期的文件！");
            } else {
                for (int j = 0; j < num.length; j++) {
                    String customerSql = "select id,customer_name as customerName,customer_phone as customerPhone,num as num,image_url as imageUrl from icon_infos " +
                            "where num='" + num[j] + "' limit 1 ";
                    QualityAssuranceInfo infos = sqlMapper.selectOne(customerSql, QualityAssuranceInfo.class);
                    String fileName = infos.getNum() + infos.getCustomerName() + infos.getCustomerPhone();
                    //患者照片的路径
                    String realPath = "D:\\8068\\apache-tomcat-8.0.30\\webapps\\ROOT\\photoScoring\\" + abbreviation + "\\" + fileTime + "\\" + fileName + "\\";
                    //临时文件夹路径
                    newPath = "D:\\8068\\apache-tomcat-8.0.30\\webapps\\ROOT\\imageScore\\" + abbreviation + "\\" + fileTime + "\\" + fileName + "\\";
                    realNewPath = "D:\\8068\\apache-tomcat-8.0.30\\webapps\\ROOT\\imageScore\\" + abbreviation + "\\" + fileTime + "\\";
                    File ff = new File(realPath);
                    File ft = new File(newPath);
                    //通过客户ID 是否找到该患者文件夹
                    System.out.println(ff.exists());
                    if (!ff.exists()) {
                        System.out.println("没有找到该患者的文件夹");
                    } else {
                        if (!ft.exists()) {//判断文件夹是否创建，没有创建则创建新文件夹
                            ft.mkdirs();
                        }
                        // 获取源文件夹当前下的文件
                        File[] files = (new File(realPath)).listFiles();
                        for (int e = 0; e < files.length; e++) {
                            if (files[e].isFile()) {
                                // 复制文件
                                copyFile(files[e], new File(newPath + File.separator + files[e].getName()));
                            }
                        }
                    }
                }
            }
        }
        //获取指定目录下的所有文件夹
        File[] array = fi.listFiles();
        for (int i = 0; i < array.length; i++) {
            if (array[i].isDirectory()) {
                getFile(array[i].getPath());
                String pathfo =getFile(array[i].getPath())+"\\";
                System.out.println(getFile(array[i].getPath()));
                String[] cmd = new String[]{"python", command, pathfo};
                System.out.println(cmd);
                getCmdOutput(cmd);  // 通过Runtime.getRuntime()执行脚本文件
                System.out.println(realUrl);
            }
        }
        return 1;
    }
    public static void deleteDirectory(File file) {
        if (file.isFile()) {
            file.delete();//清理文件
        } else {
            File list[] = file.listFiles();
            if (list != null) {
                for (File f : list) {
                    deleteDirectory(f);
                }
                file.delete();//清理目录
            }
        }
    }

//    public static void main(String[] args) throws IOException {
//        String command = "D:\\Python\\python3.6.5\\Lib\\site-packages\\tensorboard\\backend\\application.py";   // python程序的路径
//        String[] cmd = new String[]{"python", command};
//        getCmdOutput(cmd);  // 通过Runtime.getRuntime()执行脚本文件
//        System.out.println();
//    }

    public String getCmdOutput(String[] cmd) {//JAVA实现实时Process，实时获取输出
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
            process = runtime.exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String charsetName = "GB2312";
        InputStreamReader reader;
        try {
            //获取标准的输出
            reader = new InputStreamReader(process.getInputStream(), charsetName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line;
        String returnString = null;
        String errorString = null;
        String httpUrl = null;
        int rowNow = 0;
        int count = 0;
        try {
            while (true) {
                line = bufferedReader.readLine();
                //赋值第一行给返回变量
                if (line == null)
                    break;
                else {
                    if (rowNow == 2) {
                        httpUrl = line;
                    }
                    if (rowNow == 3) {
                        errorString = line;
                    }
                    String aabb = line.split("#")[0].trim();
                    if (aabb.equals("aabb")) {
                        returnString = line;
                        //参数 1 D:\8068\apache-tomcat-8.0.30\webapps\ROOT\photoScoring\JPG_2019-09-03\
                        String lineStr[] = returnString.split("#");
                        String httpUrl1 = httpUrl.substring(httpUrl.indexOf("photoScoring") + 13).replace("\\", "");
                        String aa = lineStr[1].trim();
                        String selStr = "select * from icon_infos where concat(num,customer_name,customer_phone)='" + aa + "' ";
                        List<IconInfo> listInfo = sqlMapper.selectList(selStr, IconInfo.class);
                        if (listInfo.size() == 0) {
                            return "aa";
                        } else {
                            //按 aabb # 刘紫琴13476825875 # 0 # 10 8 6 15 0 0 0 39 # 10 8 6 20 17 17 8 86 存这组照片3张
                            for (int i = 0; i < listInfo.size(); i++) {
                                int j = i + 2;
                                String curStr[];
                                IconInfo info = listInfo.get(i);
                                curStr = lineStr[j].split("\\s");
                                String interllsql = "insert into intelligent_score_details_infos select * from intelligent_score_details_info2 where id2='" + info.getId() + "'";
                                sqlMapper.insert(interllsql);
                                String delsql = "delete from intelligent_score_details_info2 where id2='" + info.getId() + "'";
                                sqlMapper.delete(delsql);
                                String sql = "insert into intelligent_score_details_info2 (id2,photo_type,A1,A2,A3,A4,A5,A6,A7,score,create_time) VALUES ('" + info.getId() + "','" + (i + 1) + "','" + curStr[1] + "','" + curStr[2] + "','" + curStr[3] + "'," +
                                        "'" + curStr[4] + "','" + curStr[5] + "','" + curStr[6] + "','" + curStr[7] + "','" + curStr[8] + "','" + DateTimeKit.now() + "')";
                                String insertSql = "update icon_infos a set a.status=1,a.score='" + curStr[8] + "' where id='" + info.getId() + "' ";
                                sqlMapper.update(insertSql);
                                sqlMapper.insert(sql);
                            }
                        }
                        count++;
                        webSocketProgress.sendMessageViews("完成", count);
                    }
                    if (aabb.equals("error_1")) {
                        returnString = line;
                        //参数 1 D:\8068\apache-tomcat-8.0.30\webapps\ROOT\photoScoring\JPG_2019-09-03\
                        String lineStr[] = returnString.split("#");
                        String httpUrl1 = httpUrl.substring(httpUrl.indexOf("photoScoring") + 13).replace("\\", "/");
                        String aa = lineStr[1].trim().substring(0, lineStr[1].trim().indexOf("_"));
                        String iconName = lineStr[1].trim().substring(lineStr[1].trim().indexOf("_") + 1);
                        String selStr = "select * from icon_infos where concat(num,customer_name,customer_phone)='" + aa + "'and icon_name='" + iconName + "' limit 1 ";
                        IconInfo listInfo = sqlMapper.selectOne(selStr, IconInfo.class);
                        if (listInfo == null) {
                            return "aa";
                        } else {
                            if ("术前".equals(iconName)) {
                                String insertSql = "update icon_infos a set a.status=1,a.cause='" + lineStr[2] + "' where id='" + listInfo.getId() + "' ";
                                sqlMapper.update(insertSql);
                            }
                            if ("术中".equals(iconName)) {
                                String insertSql = "update icon_infos a set a.status=1,a.cause='" + lineStr[2] + "' where id='" + listInfo.getId() + "' ";
                                sqlMapper.update(insertSql);
                            }
                            if ("术后".equals(iconName)) {
                                String insertSql = "update icon_infos a set a.status=1,a.cause='" + lineStr[2] + "' where id='" + listInfo.getId() + "' ";
                                sqlMapper.update(insertSql);
                            }
                        }
                        count++;
                        webSocketProgress.sendMessageViews("完成", count);
                    }
                    //returnString = line;
                    rowNow++;
                }
                System.out.println(line);
            }
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return returnString;
    }
}